package com.stgy.lease.web.admin.controller.login;

import com.stgy.lease.common.result.Result;
import com.stgy.lease.common.utils.JwtUtil;
import com.stgy.lease.model.domain.SystemUser;
import com.stgy.lease.web.admin.dto.AdminUserLoginDto;
import com.stgy.lease.web.admin.service.SystemUserService;
import com.stgy.lease.web.admin.vo.AdminCaptchaVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * ClassName:LoginController
 * Package:com.stgy.lease.web.admin.controller.login
 * Description:
 *
 * @Author:helei
 * @Create:2024/9/4 - 8:57
 */
@RestController
@RequestMapping("/admin")
@Tag(name = "管理员登录模块")
public class LoginController {

    @Autowired
    private SystemUserService systemUserService;

    //http://localhost:5174/admin/login/captcha GET
    @Operation(summary = "获取登录验证码")
    @GetMapping("/login/captcha")
    public Result<AdminCaptchaVo> captcha() {
        /*
            返回image图片 base64字符串
                base64不是压缩处理方式，图片内容交给前端时，变大了：
                    三个字节转为四个字节
            后端缓存验证码图片文本的key
         */
        return Result.ok(systemUserService.getCaptcha());
    }

    //http://localhost:5174/admin/login POST
    //{"username":"user","password":"123456","captchaKey":"b59ec43693ae491aa4dd3e30b91b3fdd",
    // "captchaCode":"VQUQ"}
    @Operation(summary = "管理员登录")
    @PostMapping("/login")
    public Result<String> adminLogin(@RequestBody AdminUserLoginDto adminUserLoginDto) {

        //登录成功 返回jwt token
        return Result.ok(systemUserService.login(adminUserLoginDto));
    }


    //http://localhost:5174/admin/info GET
    @Operation(description = "获取登录用户信息")
    @GetMapping("/info")
    public Result<Map<String, String>> info(@RequestHeader("access_token") String token, HttpServletRequest request) {
        Map<String, Object> systemUser = JwtUtil.parseToken(token, request);
        Map<String, String> map = new HashMap<>();
        map.put("avatarUrl", systemUser.get("avatar").toString());
        map.put("name", systemUser.get("name").toString());
        return Result.ok(map);
    }
}
